package suanfa;

import java.util.LinkedList;
import java.util.Queue;

public class nearestExit {
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    public int nearestExit(char[][] maze, int[] e) {
        int m=maze.length,n=maze[0].length;
        Queue<int[]> q=new LinkedList<>();
        boolean[][] vis=new boolean[m][n];
        int step=0;
        q.add(new int[]{e[0],e[1]});
        vis[e[0]][e[1]]=true;
        while(!q.isEmpty()){
            step++;
            int sz=q.size();
            for(int i=0;i<sz;i++){
                int[] t=q.poll();
                int a=t[0],b=t[1];
                for(int j=0;j<4;j++){
                    int x=a+dx[j],y=b+dy[j];
                    if(x>=0 && x<m && y>=0 && y<n && !vis[x][y] && maze[x][y]=='.'){
                        if(x==0 || x==m-1 || y==0 || y==n-1) return step;
                        q.add(new int[]{x,y});
                        vis[x][y]=true;
                    }
                }
            }
        }
        return -1;
    }
}
